<?php
class ymdian_order_cartModel extends model{
	public $base;
	public $oc_where;
	public function __construct(&$base){
		parent::__construct($base);
		$this->base=$base;
		$this->table="ymdian_order_cart";
		$this->oc_where=M('login')->userid?" (userid=".M('login')->userid." or oc_ssid='".OC_SSID."') ":"oc_ssid='".OC_SSID."' ";
		$this->oc_where.=" AND siteid=".SITEID;
	}
	
	
	public function getListByUser($w=''){
		$option=array(
			"where"=>$this->oc_where." AND siteid=".SITEID." ".$w
		);
		$data=$this->select($option);
		 
		$total_money=0;
		$total_num=0;
		if($data){
			foreach($data as $v){
				
				$ids[]=$v['productid'];
				$cart[$v['object_id']]=$v;
			}
		 	$products=M("product")->getListByIds($ids);
			foreach($data as $v){
				$total_money +=$v['amount']*$products[$v['productid']]['price'];
				$total_num+=$v['amount'];
			}
			return array("product"=>$cart,"total_money"=>$total_money,"total_num"=>$total_num);
		}
		return array("product"=>array(),"total_money"=>0,"total_num"=>0);
	}
	
	public function Cart($shopid=0){
		$where=$this->oc_where;
		if($shopid){
			$where.=" AND shopid=".$shopid;
		}
		$list=$this->select(array("where"=>$where));
		
		 
		if($list){
			foreach($list as $v){				
				$shopids[]=$v['shopid'];
				$productids[]=$v['productid'];
				$ksids[]=$v['ksid'];
				
			}
			
			if($productids){
				$products=M("product")->id_list(array("where"=>" id in("._implode($productids).") "));
				$kslist=M('product_ks')->id_list(array("where"=>"  id in("._implode($ksids).") "));
				$shoplist=M('shop')->id_shop(array("where"=>"shopid in("._implode($shopids).")"));
			}
			$total_money=0; 
			$total_num=0;
			foreach($list as $k=>$v){
			 	$total_num+=$v['amount'];
				$product=$products[$v['productid']]; 
				$v['title']=$product['title'];
				$v['imgurl']=images_site($product['imgurl']);
				if(isset($kslist[$v['ksid']])){
					$ks=$kslist[$v['ksid']];
					$v['price']=$product['lower_price']>0?$product['lower_price']:$ks['price'];
					$v['ks_title']=$ks['title'];
				}else{
					$v['price']=$product['lower_price']>0?$product['lower_price']:$product['price'];
				}
				$total_money+=$v['price']*$v['amount'];
				$shoplist[$v['shopid']]['products'][]=$v;
			}
			
			return array("list"=>$shoplist,"total_money"=>$total_money,"num"=>$total_num,"islogin"=>M("login")->userid); 
		}
		return array("list"=>false,"total_money"=>0,"num"=>0,"islogin"=>M("login")->userid); 
	}
	 
	
	
	
	
}

?>